package com.turtle3d.formallanguage.grammar.parser;

import java.util.ArrayList;

import com.turtle3d.formallanguage.grammar.Production;
import com.turtle3d.formallanguage.symbol.Symbol;
import com.turtle3d.formallanguage.symbol.SymbolClass;
import com.turtle3d.formallanguage.symbol.SymbolFactory;


/**
 * B->B[-F][+F] F->F(r*1.8)F(r*1.8)
 * 
 * @author Marek Paterczyk <marek.paterczyk@gmail.com>
 * 
 */
public class SimpleProductionParser
{
	public static Production parse(String productionString)
	{
		Production production = new Production();

		String[] sides = productionString.split("->");
		
		if(sides[0].indexOf(':')!=-1){
		String leftSide[] = sides[0].split(":");
			try
			{
				production.setProbability(Float.parseFloat(leftSide[0].trim()));
			}
			catch (NumberFormatException e)
			{
			}
			production.setLeftSide(new Symbol(leftSide[1].trim()));
		}
		else
			production.setLeftSide(new Symbol(sides[0]));
				
		
		ArrayList<SymbolClass> symbolClasses = new ArrayList<SymbolClass>();

		for (int i = 0; i < sides[1].length(); i++)
		{
			String c = (new Character(sides[1].charAt(i))).toString();

			if (i + 1 < sides[1].length() && sides[1].charAt(i + 1) == '(')
			{
				int pos1 = i + 1;
				int pos2 = sides[1].indexOf(')', pos1);
				String symbolClassName = sides[1].substring(i, pos2 + 1);
				// System.out.println(symbolClassName);
				symbolClasses.add(SymbolFactory.getSymbolFactory()
						.getSymbolClass(symbolClassName));

				i = pos2;

			}
			else
			{
				symbolClasses.add(SymbolFactory.getSymbolFactory()
						.getSymbolClass(c));
				// System.out.println(c);
			}
			// System.out.println(i);
		}

		production.setRightSide(symbolClasses);
		return production;

	}

	public static void main(String[] args)
	{

		Production p = SimpleProductionParser.parse("F->F(r*1.8)F(r*1.8)");

		System.out.println(p.getRightSide().toString());

	}
}
